﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;

namespace InnovTech.Localization
{
    public class LanguageManager
    {
        #region singleton instance
        private static LanguageManager _default;
        public static LanguageManager Default
        {
            get
            {
                if (_default == null)
                    _default = new LanguageManager();
                return _default;
            }
        }
        #endregion singleton instance

        #region events
        public event EventHandler<LanguageChangedEventArgs> LanguageChanged;
        #endregion

        #region Properties
        private CultureInfo _currentLanguage;
        public CultureInfo CurrentLanguage
        {
            get
            {
                return _currentLanguage;
            }
            set
            {
                if (_currentLanguage != value)
                {
                    CultureInfo old = _currentLanguage;
                    _currentLanguage = value;

                    Thread.CurrentThread.CurrentCulture = _currentLanguage;
                    Thread.CurrentThread.CurrentUICulture = _currentLanguage;

                    if(LanguageChanged != null)
                        LanguageChanged(this, new LanguageChangedEventArgs(old, _currentLanguage));
                }
            }
        }

        public CultureInfo DefaultLanguage { get; private set; }

        private List<CultureInfo> _avaliableLanguages;
        public List<CultureInfo> AvaliableLanguages
        {
            get 
            {
                if (_avaliableLanguages == null)
                    _avaliableLanguages = new List<CultureInfo>();
                return _avaliableLanguages;
            }
        }

        #endregion Properties

        public void RegisterLanguage(params CultureInfo[] languages)
        {
            if(languages == null) return;
            languages.ToList().ForEach( ci =>
            {
                if (!AvaliableLanguages.Any(lan => lan.IetfLanguageTag == ci.IetfLanguageTag))
                    AvaliableLanguages.Add(ci);
            });
            
        }
    }
}
